import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Button, Divider, Icon, notification, Popconfirm, Table, Upload} from "antd";
import {paginationProps, tableProps} from "../../lib/ui";
import {
    deleteLinePrice,
    getBusinessList,
    getCurrencyList,
    getFeeList,
    getTransportType,
    lineImport,
    queryLinePrice,
    showCreateLinePrice,
    showUpdateLinePrice
} from "./actions";
import CreateLinePriceModal from "./CreateLinePriceModal";
import ModifyLinePriceModal from "./ModifyLinePriceModal";
import {getCurrentOrganization, getPrincipal} from "../../lib/identity";
import {DATE_FORMAT, getStatusText} from "../../lib/func";
import {query as lineQuery} from "../line/actions";
import FilterForm from "../../components/FilterForm";

class LinePriceModal extends PureComponent {

    state = {};

    handleShowCreate = () => {
        const {dispatch} = this.props;
        dispatch(showCreateLinePrice());
        dispatch(getTransportType());
        dispatch(getCurrencyList());
        dispatch(getBusinessList());
        dispatch(getFeeList());
        dispatch(lineQuery({}));
    };
    handleUpdate = record => {
        const {dispatch} = this.props;
        dispatch(showUpdateLinePrice(record));
        dispatch(getTransportType());
        dispatch(getCurrencyList());
        dispatch(getBusinessList());
        dispatch(lineQuery({}));
    };
    handleDeleteLinePrice = id => {
        const {dispatch, model, page, pageSize} = this.props;
        dispatch(deleteLinePrice(id)).then(action => {
            if (action.error !== true) {
                dispatch(queryLinePrice({"belongId": model.id, page, pageSize}));
            }
        });
    };

    handleSearch = values => {
        const {dispatch, page, pageSize, model} = this.props;
        let fields = values;
        this.setState({...fields});
        // 日期范围查询
        if (fields.dateRange && fields.dateRange.length > 1) {
            fields.startDate = fields.dateRange[0].format(DATE_FORMAT);
            fields.endDate = fields.dateRange[1].format(DATE_FORMAT);
        }
        delete fields.dateRange;
        dispatch(queryLinePrice({"belongId": model.id, ...fields, page, pageSize}));
    };


    customRequest = (options) => {
        const {dispatch, model} = this.props;
        dispatch(lineImport({
            file: options.file,
            belongId: model.id,
            opId: getPrincipal().id,
            organizationId: getCurrentOrganization(),
            feeType: "应收"
        })).then(() => {
            notification.success({
                message: '导入成功'
            });
            dispatch(queryLinePrice({"belongId": model.id}));
        });
    };
    uploadProps = {
        showUploadList: false, name: 'file', accept: '.xls, .xlsx, .csv', customRequest: this.customRequest
    };

    onPageChange = (page, pageSize) => {
        const {dispatch, model} = this.props;
        const fields = this.state;
        dispatch(queryLinePrice({"belongId": model.id, ...fields, page, pageSize}));
    };


    render() {
        const {
            dataSource, model, loading, page, importLoading, pageSize, calculateType, totalElements,
        } = this.props;
        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) => this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };
        const columns = [{
            title: "业务类型", dataIndex: "businessType", width: "150px",
        }, {
            title: "单位", dataIndex: "unit", width: "80px",
        }, {
            title: "起始站", dataIndex: "originPlace", width: "150px",
        }, {
            title: "目的站", dataIndex: "destPlace", width: "150px",
        }, {
            title: "出境口岸", dataIndex: "departurePort", width: "150px",
        }, {
            title: "费用名称", dataIndex: "feeName", width: "150px",
        }, {
            title: "费用性质", dataIndex: "feeType", width: "150px",
        }, {
            title: "币种", dataIndex: "currency", width: "150px",
        }, {
            title: "单价/KG", dataIndex: "price", width: "150px",
        }, {
            title: "单价/CBM", dataIndex: "price2", width: "150px",
        }, {
            title: "重泡比", dataIndex: "pb", width: "90px", render: (text) => ("1:" + text)
        }, {
            title: "计费方式",
            dataIndex: "calculateType",
            width: "150px",
            render: (text) => getStatusText(text, calculateType)
        }, {
            title: "有效期", dataIndex: "expirationDate", width: "200px", render: (text, record) => <span>
                    {record.startDate} 至 {record.endDate}
                </span>
        }, {
            title: "所属抬头", dataIndex: "organizationName", width: "150px",
        }, {
            title: "创建人", dataIndex: "opName", width: "150px",
        }, {
            title: "备注", dataIndex: "remark", width: "200px", ellipsis: true
        }, {
            title: '功能',
            dataIndex: '',
            key: 'x',
            width: 80,
            align: 'center',
            fixed: 'right',
            render: (text, record) => <span>
                    <a onClick={() => this.handleUpdate(record)}><Icon type="edit"/></a>
                    <Divider type="vertical"/>
                    <Popconfirm title="确定移除此线路价格?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDeleteLinePrice(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>
        }];

        const filterSchema = [{
            key: 'originPlace',
            field: 'originPlace',
            type: 'text',
            expandable: true,
            width: 200,
            title: '起始站',
            fieldOptions: {
                initialValue: this.state.originPlace
            }
        }, {
            key: 'destPlace',
            field: 'destPlace',
            type: 'text',
            expandable: true,
            width: 200,
            title: '目的站',
            fieldOptions: {
                initialValue: this.state.destPlace
            }
        }, {
            key: 'dateRange',
            field: 'dateRange',
            type: 'dateRangePicker',
            expandable: true,
            title: '有效期范围',
            fieldOptions: {
                initialValue: this.state.dateRange
            }
        }];

        /*if (getPrincipal().admin) {
            columns.push(
                {
                    title: '功能',
                    dataIndex: '',
                    key: 'x',
                    width: 80,
                    align: 'center',
                    fixed: 'right',
                    render: (text, record) => <span>
                    <a onClick={() => this.handleUpdate(record)}><Icon type="edit"/></a>
                    <Divider type="vertical"/>
                    <Popconfirm title="确定移除此线路价格?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDeleteLinePrice(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>
                }
            );
        }*/
        return (

            <div>
                <div className="actions">
                    <Button onClick={() => this.handleShowCreate()}>新增</Button>
                    <Button href="/static/线路导入模板.xlsx" target="_blank">下载导入模板</Button>
                    <Upload {...this.uploadProps}>
                        <Button disabled={importLoading}>
                            <Icon type="upload"/> 导入
                        </Button>
                    </Upload>
                </div>
                <FilterForm schema={filterSchema} callback={this.handleSearch} loading={loading}/>
                <h3 style={{color: 'red'}}>计费规则：根据订单相同业务类型、计费方式、起始站、目的站、费用名称，并且在有效期范围内才符合计费规则（注意：国际版列按照班列日期，综合物流按照提货日期来判断是否符合线路有效期）</h3>
                <Table
                    {...tableProps}
                    columns={columns}
                    scroll={{x: 1500}}
                    pagination={tablePagination}
                    dataSource={dataSource}
                    loading={loading}
                />
                <CreateLinePriceModal modelId={model.id}/>
                <ModifyLinePriceModal/>
            </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.client.listLinePrice,
        model: state.client.modify.model,
        calculateType: state.common.calculateType,
        businessList: state.client.list.businessList,
    };
};

export default connect(mapStateToProps)(LinePriceModal);
